import React, {Component} from 'react';
import PropTypes from "prop-types";
import axios from "axios";

class Main extends Component {
    state = {
        initView: true,
        loading: false,
        users: null,
        errorMsg: null
    };
    static propTypes = {
        searchVal: PropTypes.string.isRequired
    };

    async componentWillReceiveProps(newProps) {
        const {searchVal} = newProps;
        this.setState({
            initView: false,
            loading: true
        });
        const url = "https://api.github.com/search/users";
        let data = await axios.get(url, {
            params: {
                q: searchVal
            }
        });
        console.log(data.data);
        this.setState({
            loading:false,
            users:data.data.items
        })
    }

    render() {
        const {initView, loading, users, errorMsg} = this.state;
        if (initView) {
            return (<h2>请输入关键字搜索!</h2>)
        } else if (loading) {
            return (<h2>正在请求中...</h2>)
        } else if (errorMsg) {
            return (<h2>{errorMsg}</h2>)
        } else if (users) {
            return (
                <div className="row">
                    {
                        users.map((val, index) => (
                            <div className="card" key={val.id}>
                                <a href={val.html_url} target="_blank">
                                    <img src={val.avatar_url}
                                         style={{width: "100px"}}/>
                                </a>
                                <p className="card-text">{val.login}</p>
                            </div>
                        ))
                    }
                </div>
            );
        }
    }
}

export default Main;